/* A stack
   Written by ZHANG JUN
   2000.5.2
*/
#include "alloc.h"
#include "common.h"

/* The stack's element type is int   */
typedef struct{
	int *base;
	int *top;
	unsigned stacksize;
}IntStack;

Status InitIntStack(IntStack *ps,unsigned size)
{
 ps->base=(int *)malloc(size*sizeof(int));
 if(!ps->base)
 exit(OVERFLOW);
 ps->top=ps->base;
 ps->stacksize=size;
 return OK;
}

void DestoryIntStack(IntStack *ps)
{
 free(ps->base);
 ps->stacksize=0;
}

void ClearIntStack(IntStack *ps)
{
 ps->top=ps->base;
}

Bool IsIntStackEmpty(IntStack s)
{
 return s.base==s.top;
}

unsigned IntStackLength(IntStack s)
{
 return s.top-s.base;
}

int GetIntTop(IntStack s)
{
 if(IsIntStackEmpty(s))
 return 0;
 return *(s.top-1);
}

Status PushInt(IntStack *ps,int e)
{
 if(ps->top-ps->base>=ps->stacksize)
  return OVERFLOW;
 *(ps->top)=e;
 ps->top++;
 return OK;
}

Status PopInt(IntStack *ps,int *pe)
{
 if(IsIntStackEmpty(*ps))
  return ERROR;
 *pe=*(--ps->top);
  return OK;
}

/********************************************************************/
/* The stack's element type is char */

typedef struct{
	char *base;
	char *top;
	unsigned stacksize;
}CharStack;

Status InitCharStack(CharStack *ps,unsigned size)
{
 ps->base=(char *)malloc(size*sizeof(char));
 if(!ps->base)
  return OVERFLOW;
 ps->top=ps->base;
 ps->stacksize=size;
 return OK;
}

void DestoryCharStack(CharStack *ps)
{
 free(ps->base);
 ps->stacksize=0;
}

void ClearCharStack(CharStack *ps)
{
 ps->top=ps->base;
}

Bool IsCharStackEmpty(CharStack s)
{
 return s.base==s.top;
}

unsigned CharStackLength(CharStack s)
{
 return s.top-s.base;
}

char GetCharTop(CharStack s)
{
 if(IsCharStackEmpty(s))
 return 0;
 return *(s.top-1);
}

Status PushChar(CharStack *ps,char e)
{
 if(ps->top-ps->base>=ps->stacksize)
  return OVERFLOW;
 *(ps->top)=e;
 ps->top++;
 return OK;
}

Status PopChar(CharStack *ps,char *pe)
{
 if(IsCharStackEmpty(*ps))
  return ERROR;
 *pe=*(--ps->top);
  return OK;
}

